#![allow(non_snake_case)]
mod message_provider;

pub use message_provider::*;

use leptos::prelude::*;
use icondata as i;
use leptos_icons::*;
use thaw_utils::{class_list, ArcCallback, BoxOneCallback};

#[derive(Default, Clone)]
pub enum MessageVariant {
    #[default]
    Info,
    Success,
    Warning,
    Error,
}
impl MessageVariant {
    fn icon(&self) -> i::Icon {
        match self {
            MessageVariant::Info => i::AiInfoCircleOutlined,
            MessageVariant::Success => i::AiCheckCircleOutlined,
            MessageVariant::Warning => i::BiErrorCircleRegular,
            MessageVariant::Error => i::VsError,
        }
    }
    fn color_class(&self) -> &'static str {
        match self {
            MessageVariant::Info => "alert-info",
            MessageVariant::Success => "alert-success",
            MessageVariant::Warning => "alert-warning",
            MessageVariant::Error => "alert-error",
        }
    }
}

#[component]
fn Message(message: MessageType, #[prop(into)] on_close: BoxOneCallback<usize>) -> impl IntoView {
    let (id, content, variant, MessageOptions { duration, closable }) = message;
    let is_show = RwSignal::new(true);
    let close_msg=ArcCallback::new(move||{
        is_show.set(false);
        on_close(id);
    });
    if !duration.is_zero() {
        let close_msg=close_msg.clone();
        set_timeout(
            move || {
                close_msg();
            },
            duration,
        );
    }
    let close_button = move||{
        let close_msg=close_msg.clone();
        if closable {
            Some(view! {
                <div on:click=move|_|{
                    close_msg()
                }>
                    <Icon icon=i::AiCloseOutlined/>
                </div>
            })
        } else {
            None
        }
    };
    view! {
        <div role="alert" class=class_list!["alert",variant.color_class()]>
            <Icon icon=variant.icon()/>
            <span>{content}</span>
            {close_button}
        </div>
    }
}


